package cn.com.css.taxInspection.common.sysjob.service;

import cn.com.css.taxInspection.gt3.entity.JcDsrwTaskEntity;
import cn.com.css.taxInspection.gt3.mapper.JcDsrwTaskMapper;
import cn.com.css.taxInspection.util.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;

import java.util.concurrent.ScheduledFuture;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class SchedulerService {

    private final ThreadPoolTaskScheduler taskScheduler;
    private final JcDsrwTaskMapper jcDsrwTaskMapper;

    public SchedulerService(ThreadPoolTaskScheduler taskScheduler, JcDsrwTaskMapper jcDsrwTaskMapper) {
        this.taskScheduler = taskScheduler;
        this.jcDsrwTaskMapper = jcDsrwTaskMapper;
    }

    private static final Logger logger = LoggerFactory.getLogger(SchedulerService.class);


    //存储定时任务的容器
    private final Map<String, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();


    // 项目启动时加载任务
    @PostConstruct
    public void init() {
        logger.info("——————————系统定时任务启动——————————");
        List<JcDsrwTaskEntity> taskList = jcDsrwTaskMapper.selectAllEnabled();
        for (JcDsrwTaskEntity task : taskList) {
            startTask(task);
        }
    }

    public void startTask(JcDsrwTaskEntity task) {
        Runnable runnable = () -> {
            try {
                // 动态获取 Bean，并反射调用方法
                Object bean = SpringContextUtils.getBean(task.getBeanName());
                Method method = bean.getClass().getMethod(task.getMethodName());
                method.invoke(bean);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        };

        ScheduledFuture<?> future = taskScheduler.schedule(
                runnable,
                new CronTrigger(task.getCronExpression())
        );

        scheduledTasks.put(task.getId(), future);
    }

    // 停止任务
    public void stopTask(String taskId) {
        ScheduledFuture<?> future = scheduledTasks.get(taskId);
        if (future != null) {
            future.cancel(true);
        }
        scheduledTasks.remove(taskId);
    }

    // 重启任务（修改 cron 后调用）
    public void restartTask(JcDsrwTaskEntity jcDsrwTaskEntity) {
        stopTask(jcDsrwTaskEntity.getId());
        startTask(jcDsrwTaskEntity);
    }

    // 立即执行任务
    public void runNow(JcDsrwTaskEntity jcDsrwTaskEntity) {
        try {
            Object bean = SpringContextUtils.getBean(jcDsrwTaskEntity.getBeanName());
            Method method = bean.getClass().getMethod(jcDsrwTaskEntity.getMethodName());
            method.invoke(bean);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
